#!/usr/bin/env python3
"""
小红书AI运营工具启动脚本

使用方法:
    python start.py              # 默认启动
    python start.py --dev        # 开发模式
    python start.py --prod       # 生产模式
    python start.py --port 8080  # 指定端口
"""

import argparse
import os
import sys
import uvicorn
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))


def check_dependencies():
    """检查依赖是否安装"""
    required_packages = [
        'fastapi',
        'uvicorn',
        'sqlalchemy',
        'pymysql',
        'pydantic',
        'requests',
        'boto3',
        'playwright'
    ]
    
    missing_packages = []
    
    for package in required_packages:
        try:
            __import__(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n请运行以下命令安装依赖:")
        print("pip install -r requirements.txt")
        print("playwright install")
        return False
    
    print("✅ 所有依赖包已安装")
    return True


def check_environment():
    """检查环境配置"""
    env_file = project_root / '.env'
    
    if not env_file.exists():
        print("❌ 未找到 .env 配置文件")
        print("请复制 .env.example 并根据实际情况修改配置")
        return False
    
    print("✅ 环境配置文件存在")
    
    # 打印所有环境变量
    print("\n📋 当前环境变量:")
    print("=" * 60)
    for key, value in sorted(os.environ.items()):
        # 隐藏敏感信息
        if any(sensitive in key.upper() for sensitive in ['PASSWORD', 'SECRET', 'KEY', 'TOKEN']):
            masked_value = value[:4] + '*' * (len(value) - 8) + value[-4:] if len(value) > 8 else '*' * len(value)
            print(f"{key}: {masked_value}")
        else:
            print(f"{key}: {value}")
    print("=" * 60)
    
    # 检查关键配置项
    from app.core.config import settings
    
    issues = []
    
    if 'localhost' in settings.DATABASE_URL and 'password' in settings.DATABASE_URL:
        issues.append("数据库使用默认配置，请修改为实际配置")
    
    # OpenAI API Key 是可选的，不配置时使用模拟数据
    # if settings.OPENAI_API_KEY == "your-openai-api-key-here":
    #     issues.append("OpenAI API Key 未配置")
    
    if settings.SECRET_KEY == "your-secret-key-change-this-in-production":
        issues.append("安全密钥使用默认值，生产环境请修改")
    
    if issues:
        print("⚠️  配置警告:")
        for issue in issues:
            print(f"   - {issue}")
    
    return True


def check_services():
    """检查外部服务连接"""
    print("🔍 检查外部服务...")
    
    # 检查数据库连接
    try:
        from app.db.session import engine
        from sqlalchemy import text
        
        with engine.connect() as conn:
            conn.execute(text("SELECT 1"))
        print("✅ 数据库连接正常")
    except Exception as e:
        print(f"❌ 数据库连接失败: {e}")
        print("请检查MySQL服务是否启动，配置是否正确")
        return False
    
    # 检查存储服务
    try:
        from app.services.storage_service import storage_service
        if storage_service.is_available():
            print("✅ 对象存储服务正常")
        else:
            print("⚠️  对象存储服务不可用")
    except Exception as e:
        print(f"⚠️  对象存储检查失败: {e}")
    
    # 检查AI服务
    try:
        from app.services.ai_service import ai_service
        if ai_service.is_available():
            print("✅ AI服务正常")
        else:
            print("⚠️  AI服务不可用（可能未配置API Key）")
    except Exception as e:
        print(f"⚠️  AI服务检查失败: {e}")
    
    return True


def create_tables():
    """创建数据库表"""
    try:
        from app.db.session import engine, Base
        Base.metadata.create_all(bind=engine)
        print("✅ 数据库表创建/更新完成")
        return True
    except Exception as e:
        print(f"❌ 数据库表创建失败: {e}")
        return False


def main():
    parser = argparse.ArgumentParser(description='小红书AI运营工具启动脚本')
    parser.add_argument('--dev', action='store_true', help='开发模式')
    parser.add_argument('--prod', action='store_true', help='生产模式')
    parser.add_argument('--port', type=int, default=8000, help='端口号')
    parser.add_argument('--host', default='0.0.0.0', help='主机地址')
    parser.add_argument('--skip-checks', action='store_true', help='跳过环境检查')
    
    args = parser.parse_args()
    
    print("🚀 小红书AI运营工具启动中...")
    print("=" * 50)
    
    if not args.skip_checks:
        # 检查依赖
        if not check_dependencies():
            sys.exit(1)
        
        # 检查环境配置
        if not check_environment():
            sys.exit(1)
        
        # 创建数据库表
        if not create_tables():
            sys.exit(1)
        
        # 检查服务
        check_services()
    
    print("=" * 50)
    
    # 确定运行模式
    if args.prod:
        reload = False
        log_level = "info"
        print("🔧 运行模式: 生产环境")
    elif args.dev:
        reload = True
        log_level = "debug"
        print("🔧 运行模式: 开发环境")
    else:
        reload = True
        log_level = "info"
        print("🔧 运行模式: 默认")
    
    print(f"🌐 服务地址: http://{args.host}:{args.port}")
    print(f"📚 API文档: http://{args.host}:{args.port}/docs")
    print(f"❤️  健康检查: http://{args.host}:{args.port}/health")
    print("=" * 50)
    
    try:
        # 启动服务
        uvicorn.run(
            "app.main:app",
            host=args.host,
            port=args.port,
            reload=reload,
            log_level=log_level,
            access_log=True
        )
    except KeyboardInterrupt:
        print("\n👋 服务已停止")
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()